<script setup lang="ts">
import {
  type ColProps,
  FormInstance,
  Message,
  ValidatedError,
} from "@arco-design/web-vue";
import useLoginStroe from "@/stores/modules/useLoginStroe.ts";
import type { LoginSubmitType } from "@/types/loginType.ts";
import type { FormRule } from "@/types/commonType.ts";
import { useI18n } from "vue-i18n";  
import { reactive, ref, onMounted, nextTick, onUnmounted } from "vue";
import Local from "@/utils/local";
import { useRouter } from "vue-router";
import { getPhoneLogin } from "@/services/setting";
import { buildRoutes } from "@/utils";
import useLayoutStore from "@/stores/modules/useLayoutStore.ts";
import matchRules from "@/utils/Regexp";
defineProps<{
  labelColProps: ColProps;
  wrapperColProps: ColProps;
}>();

const { t } = useI18n();

const { setList, setTabList } = useLayoutStore();

const { setCode, getCode, submit, setIsAccountOrPhone } = useLoginStroe();

const router = useRouter();

const formRef = ref<FormInstance>();

const formModel = reactive<LoginSubmitType>({
  username: "",
  password: "",
  captcha: "",
  checkKey: "",
});

const rules: FormRule<keyof Omit<LoginSubmitType, "checkKey">> = {
  username: {
    required: true,
    message: "请输入账号",
  },
  password: [
    {
      required: true,
      message: "请输入密码",
    },
  ],
  captcha: {
    required: true,
    message: "请输入验证码",
  },
};

const handleSubmit = () => {
  formRef.value?.validate(
    (errors: undefined | Record<string, ValidatedError>) => {
      if (errors === undefined) {
        submit({
          ...formModel,
          checkKey: getCode().key,
        })
          .then((res) => {
            Local.localSave("token", res.token);
            Local.localSave("user", JSON.stringify(res.user));
            Local.localSave(
              "menuList",
              JSON.stringify(res.permissionTreeVOList)
            );
            Local.localSave("roleId", res.roleId);
            console.log(res.roleCode)
            Local.localSave("roleCode", res.roleCode);
            Local.localSave("defaultRouter", res.defaultRouter);
            setList(res.permissionTreeVOList);
            setTabList(res.defaultRouter);
            // 如果有错误 就 刷新验证码
            try {
              buildRoutes(res.permissionTreeVOList);
              if (res.defaultRouter) {
                nextTick(() => {
                  router.push(res.defaultRouter);
                });
              } else {
                Message.warning("请设置当前角色默认首页");
              }
            } catch (error) {
              Message.error("登录失败，请检查路由是否正确");
              setCode();
            }
          })
          // .catch((err) => {
          //   Message.error(err.msg);
          // });
      }
    }
  );
};

const isPhone = ref("");
const isPhoneLogin = () => {
  getPhoneLogin().then((res) => {
    if (res.code === 200) {
      isPhone.value = res.data.paramValue;
    }
  });
};

const refreshCaptcha = () => {
  setCode();
};
const timer = ref(null);
onMounted(() => {
  isPhoneLogin();
  timer.value = setInterval(refreshCaptcha, 60000); // 每分钟刷新一次验证码
});

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value); // 清除定时器
  }
});
</script>

<template>
  <a-form
    :rules="rules"
    ref="formRef"
    :model="formModel"
    :label-col-props="labelColProps"
    :wrapper-col-props="wrapperColProps"
  >
    <a-form-item field="username">
      <a-input
        allow-clear
        v-model="formModel.username"
        :placeholder="t('login.user.placeholder')"
      />
    </a-form-item>
    <a-form-item field="password">
      <a-input-password
        allow-clear
        v-model="formModel.password"
        :placeholder="t('login.pwd.placeholder')"
      />
    </a-form-item>
    <a-form-item field="captcha">
      <a-input
        allow-clear
        v-model="formModel.captcha"
        :placeholder="t('login.code.placeholder')"
      >
        <template #append>
          <img
            :src="getCode().image"
            alt="验证码"
            @click="setCode()"
          />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item>
      <a-button
        style='user-select: none;'
        type="primary"
        long
        @click="handleSubmit"
      >{{ t('login.button') }}</a-button>
    </a-form-item>
    <a-form-item>
      <a-button
        v-if="isPhone === '1'"
        type="primary"
        long
        style='user-select: none;'
        @click="setIsAccountOrPhone(false)"
      >{{ t('login.phoneButton') }}</a-button>
    </a-form-item>
  </a-form>
</template>

<style scoped lang="scss">
:deep(.arco-form-item-message) {
  color: #ff9854 !important;
}
:deep(.arco-btn-primary) {
  background: linear-gradient(to right, #6593fc, #004cfd);
  border: none;
}
</style>
